package com.ihisomp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ihisomp.base.Page;
import com.ihisomp.base.Result;
import com.ihisomp.dto.OrgTreeDto;
import com.ihisomp.dto.SysHospitalDto;
import com.ihisomp.dto.SysPathTreeDto;
import com.ihisomp.entity.SysHospital;
import com.ihisomp.entity.SysMgrOrgPage;
import com.ihisomp.mapper.SysHospitalMapper;
import com.ihisomp.service.ISysHospitalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ihisomp.service.ISysMgrOrgPageService;
import com.ihisomp.util.ComUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 医疗机构信息表 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-01-12
 */
@Service
public class SysHospitalServiceImpl extends ServiceImpl<SysHospitalMapper, SysHospital> implements ISysHospitalService {

    @Autowired
    private ISysMgrOrgPageService sysMgrOrgPageService;

    /**
     * 获取机构树形集合数据
     *
     * @return
     */
    @Override
    public Result getOrgTree() {
        List<OrgTreeDto> list = baseMapper.getOrgTree();
        if (list.size() <= 0) {
            return Result.error("没有找到机构数据！");
        }
        List<OrgTreeDto> orgList = new ArrayList();

        // 查找一级菜单路径
        for (int i = 0; i < list.size(); i++) {
            // 一级菜单没有ParentOrgKey
            if (StringUtils.isBlank(list.get(i).getParentOrgKey())) {
                orgList.add(list.get(i));
            }
        }
        // 递归查询子菜单
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (OrgTreeDto org : orgList) {
            org.setChildren(getChild(org.getOrgKey(), list));
        }
        Map<String, List> map = new HashMap<>();
        map.put("org", orgList);
        // 增加根节点
        OrgTreeDto root = new OrgTreeDto();
        root.setOrgKey("ROOT");
        root.setOrgName("机构列表");
        root.setChildren(orgList);
        List<OrgTreeDto> orgRoot = new ArrayList();
        orgRoot.add(root);
        return Result.ok(orgRoot);
    }

    /**
     * 递归查找子菜单
     *
     * @param id
     * @param rootPath
     * @return
     */
    private List<OrgTreeDto> getChild(String id, List<OrgTreeDto> rootPath) {
        // 子菜单
        List<OrgTreeDto> childList = new ArrayList<>();
        for (OrgTreeDto path : rootPath) {
            // 遍历所有节点，将父机构id与传过来的id比较
            if (StringUtils.isNotBlank(path.getParentOrgKey())) {
                if (path.getParentOrgKey().equals(id)) {
                    childList.add(path);
                }
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }


    /**
     * 新增数据
     *
     * @param sysHospitalDto
     * @return
     */
    @Override
    public Result add(SysHospitalDto sysHospitalDto) {
        if (sysHospitalDto == null || StringUtils.isBlank(sysHospitalDto.getOrgKey())) {
            return Result.error("机构代码不能为空！");
        }
        if (StringUtils.isBlank(sysHospitalDto.getOrgName())) {
            return Result.error("机构名称不能为空！");
        }
        if (baseMapper.selectById(sysHospitalDto.getOrgKey()) != null) {
            return Result.error("机构数据已经存在！");
        }
        SysHospital sysHospital = new SysHospital();
        BeanUtils.copyProperties(sysHospitalDto, sysHospital);
        sysHospital.setActiveFlg(1);
        sysHospital.setCreateTime(ComUtil.getDateTimeString());
        if (baseMapper.insert(sysHospital) > 0) {
            return Result.ok();
        }
        return Result.error("新增机构数据失败！");
    }

    /**
     * 更新状态
     *
     * @param orgKey
     * @param status
     * @return
     */
    @Override
    public Result updateStatus(String orgKey, int status) {
        SysHospital sysHospital = baseMapper.selectById(orgKey);
        if (sysHospital == null) {
            return Result.error("无查询机构数据！");
        }
        if (status == 0) {
            sysHospital.setActiveFlg(1);
        } else {
            sysHospital.setActiveFlg(0);
        }
        if (baseMapper.updateById(sysHospital) > 0) {
            return Result.ok();
        }
        return Result.error("更新机构数据失败！");
    }

    /**
     * 更新数据
     *
     * @param orgKey
     * @param sysHospitalDto
     * @return
     */
    @Override
    public Result update(String orgKey, SysHospitalDto sysHospitalDto) {
        if (sysHospitalDto.getOrgKey() == null) {
            sysHospitalDto.setOrgKey(orgKey);
        }
        SysHospital sysHospital = new SysHospital();
        BeanUtils.copyProperties(sysHospitalDto, sysHospital);
        if (baseMapper.updateById(sysHospital) > 0) {
            return Result.ok();
        }
        return Result.error("更新机构数据失败！");
    }

    /**
     * 查询数据
     *
     * @param orgKey
     * @return
     */
    @Override
    public Result get(String orgKey) {
        return Result.ok(baseMapper.selectById(orgKey));
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @param sysHospitalDto
     * @return
     */
    @Override
    public Result search(long page, long size, SysHospitalDto sysHospitalDto) {
        if (sysHospitalDto == null) {
            sysHospitalDto = new SysHospitalDto();
        }
        // 分页查询
        IPage<SysHospital> data = baseMapper.searchPage(new Page<SysHospital>(page, size), sysHospitalDto);
        return Result.ok(data);
    }

    /**
     * 管理公司列表
     *
     * @return
     */
    @Override
    public Result selectManageList() {
        List<SysHospitalDto> list = baseMapper.selectManageList();
        SysHospitalDto dto = new SysHospitalDto();
        dto.setOrgKey("");
        dto.setOrgName("");
        list.add(0, dto);
        return Result.ok(list);
    }

    /**
     * 根据机构代码查询机构程序权限
     *
     * @param orgKey
     * @return
     */
    @Override
    public Result getPathByOrgKey(String orgKey) {
        return Result.ok(sysMgrOrgPageService.getPathByOrgKey(orgKey));
    }

    /**
     * 更新机构程序权限
     *
     * @param orgKey
     * @param orgPathList
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    @Override
    public Result updateOrgPath(String orgKey, List<SysPathTreeDto> orgPathList) {
        if (orgPathList == null || orgPathList.size() == 0) {
            return Result.error("机构程序权限不能为空！");
        }
        if (sysMgrOrgPageService.deletePathByOrgKey(orgKey) < 0) {
            return Result.error("更新机构程序权限失败！");
        }
        SysMgrOrgPage sysMgrOrgPage = new SysMgrOrgPage();
        sysMgrOrgPage.setOrgKey(orgKey);
        for (int i = 0; i < orgPathList.size(); i++) {
            if ("ROOT".equals(orgPathList.get(i).getId())) {
                continue;
            }
            sysMgrOrgPage.setOrgPageKey(ComUtil.createPrimaryKey());
            sysMgrOrgPage.setPagePathKey(orgPathList.get(i).getId());
            if (!sysMgrOrgPageService.save(sysMgrOrgPage)) {
                return Result.error("更新机构程序权限失败！");
            }
        }
        return Result.ok();


    }

    /**
     * 查询机构程序权限树形数据
     *
     * @param orgKey
     * @return
     */
    @Override
    public Result getOrgPathTree(String orgKey) {
        List<SysPathTreeDto> list = sysMgrOrgPageService.getPathByOrgKey(orgKey);
        if (list.size() <= 0) {
            return Result.error("该机构未分配程序权限！");
        }
        List<SysPathTreeDto> pathList = new ArrayList();
        // 查找一级菜单路径
        for (int i = 0; i < list.size(); i++) {
            // 一级菜单没有pid
            if (StringUtils.isBlank(list.get(i).getPid())) {
                pathList.add(list.get(i));
            }
        }
        // 递归查询子菜单
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (SysPathTreeDto path : pathList) {
            path.setChildren(getSysPathChild(path.getId(), list));
        }
        Map<String, List> map = new HashMap<>();
        map.put("path", pathList);
        // 增加根节点
        SysPathTreeDto root = new SysPathTreeDto();
        root.setId("ROOT");
        root.setName("系统路径");
        root.setChildren(pathList);
        List<SysPathTreeDto> pathRoot = new ArrayList();
        pathRoot.add(root);
        return Result.ok(pathRoot);
    }

    /**
     * 递归查找子菜单
     *
     * @param id
     * @param rootPath
     * @return
     */
    private List<SysPathTreeDto> getSysPathChild(String id, List<SysPathTreeDto> rootPath) {
        // 子菜单
        List<SysPathTreeDto> childList = new ArrayList<>();
        for (SysPathTreeDto path : rootPath) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StringUtils.isNotBlank(path.getPid())) {
                if (path.getPid().equals(id)) {
                    childList.add(path);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysPathTreeDto path : childList) {
            // 没有url子菜单还有子菜单
            if (StringUtils.isNotBlank(path.getUrl())) {
                // 递归
                path.setChildren(getSysPathChild(path.getId(), rootPath));
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
